<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="40%" :close-on-click-modal="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      v-loading="formLoading"
      scroll-to-error
    >
      <el-form-item label="关联设备号" prop="equipmentNo">
        <el-input v-model="formData.equipmentNo" placeholder="多台设备已','隔开'" />
      </el-form-item>
       <el-form-item label="设置引流图片" prop="drainagePic">
         <UploadImg v-model="formData.drainagePic" :limit="1" />
       </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { reactive, ref, nextTick, onMounted, onUnmounted, watch } from 'vue'
import * as DeliveryPickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore/index'
import { assign } from 'lodash-es' // Ensure lodash-es is imported if used elsewhere or add it

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formRef = ref()
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  resetForm() // 重置表单
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      // 注意：密码通常不在编辑时回显
      const data = await DeliveryPickUpStoreApi.getDeliveryPickUpStore(id)
      console.log('API Data:', data); // Log API response

      // 赋值给 formData
      formData.value = {
        ...data
      };
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })


const formData = ref()

const formRules = reactive({
})

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) {
      message.warning("请检查表单必填项！");
      return
  }
  formLoading.value = true
  try {
    // 准备提交的数据
    const dataToSubmit = {
      ...formData.value,
    }
    if (dataToSubmit.id) {
      await DeliveryPickUpStoreApi.updateDeliveryPickUpStore(dataToSubmit)
    } else {
      await DeliveryPickUpStoreApi.createDeliveryPickUpStore(dataToSubmit)
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = assign({}) // Use assign for proper reset
  formRef.value?.resetFields()
}


onMounted(() => {
})
</script>

<style scoped lang="scss">
</style>
